package com.xique.park.service.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.bean.domain.BaseUser;
import com.xique.park.bean.domain.ParkCar;
import com.xique.park.bean.domain.ParkUpdateCarLog;
import com.xique.park.bean.domain.User;
import com.xique.park.bean.dto.ParkUserDTO;
import com.xique.park.bean.request.app.ParkCarAddRequest;
import com.xique.park.bean.request.app.ParkCarEditRequest;
import com.xique.park.bean.request.app.ParkUserListRequest;
import com.xique.park.bean.request.app.ParkUserUniqueCheckRequest;
import com.xique.park.bean.request.web.car.ParkUserSaveRequest;
import com.xique.park.bean.request.web.user.AddUserRequest;
import com.xique.park.bean.request.web.user.SelectParkUserRequest;
import com.xique.park.bean.request.web.user.UpdateUserRequest;
import com.xique.park.bean.search.app.ParkUserListSearch;
import com.xique.park.bean.vo.app.ParkUserVo;
import com.xique.park.bean.vo.web.parkUser.UserVo;
import com.xique.park.constant.DictConstant;
import com.xique.park.service.biz.service.IParkUserBizService;
import com.xique.park.service.biz.service.IUserAndBaseUserBizService;
import com.xique.park.service.service.IBaseUserService;
import com.xique.park.service.service.IParkCarService;
import com.xique.park.service.service.IUserService;
import com.xique.park.service.service.ParkUpdateCarLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ParkUserBizServiceImpl implements IParkUserBizService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseUserService baseUserService;

    @Autowired
    private IParkCarService parkCarService;


    @Autowired
    private ParkUpdateCarLogService parkUpdateCarLogService;

    @Autowired
    private IUserAndBaseUserBizService userAndBaseUserBizService;

    /**
     * 查询车主列表
     * 1、根据request条件查询user；
     * 2、关联c_base_user表；
     */
    @Override
    public AjaxResult getParkUserList(ParkUserListRequest request) {
        ParkUserListSearch search = new ParkUserListSearch();
        search.setParkId(SecurityUtils.getParkId());
        search.setUserName(request.getUserName());
        search.setParam(request.getParam());
        search.setPhone(request.getPhone());
        search.setAddress(request.getAddress());
        List<ParkUserDTO> parkUserDTOList = userService.getParkUserList(search);
        Map<String, Object> map = new HashMap<>(1);
        List<ParkUserVo> vos = parkUserDTOList.stream().map(result -> {
            ParkUserVo vo = new ParkUserVo();
            vo.setUserId(result.getParkUserId());
            vo.setParkId(SecurityUtils.getParkId());
            vo.setUserName(result.getUserName());
            vo.setPhone(result.getPhone());
            vo.setAddress(result.getAddress());
            vo.setUserRemark(result.getUserRemark());
            vo.setTelephone(result.getTelephone());
            return vo;
        }).collect(Collectors.toList());
        map.put("list", vos);
        map.put("total", vos.size());
        return AjaxResult.success(map);
    }

    @Override
    public BaseUser getParkUser(Long parkUserId) {
        User user = userService.selectUserById(parkUserId);
        BaseUser baseUser = new BaseUser();
        if (null != user) {
            if (null != user.getBaseUserId()) {
                baseUser = baseUserService.selectBaseUserById(user.getBaseUserId());
            } else {
                //为了把旧平台的用户在base_user中保存一份做的操作；
                baseUser = new BaseUser();
                baseUser.setAddress(user.getAddress());
                baseUser.setCellphone(user.getPhone());
                baseUser.setUserName(user.getUserName());
                baseUserService.insertBaseUser(baseUser);
                user.setBaseUserId(baseUser.getId());
                userService.updateUser(user);
            }
        }
        return baseUser;
    }

    @Override
    public List<ParkUserDTO> getParkUserIdList(ParkUserListSearch search) {
        return userService.getParkUserList(search);
    }

    @Override
    public AjaxResult checkPhoneUnique(ParkUserUniqueCheckRequest request) {
        ParkUserListSearch search = new ParkUserListSearch();
        search.setParkId(SecurityUtils.getParkId());
        search.setUniquePhone(request.getPhone());
        List<ParkUserDTO> parkUserDTOList = userService.getParkUserList(search);
        if (CollectionUtils.isNotEmpty(parkUserDTOList)) {
            Map<String, Object> map = new HashMap<>(1);
            List<ParkUserVo> vos = parkUserDTOList.stream().map(result -> {
                ParkUserVo vo = new ParkUserVo();
                vo.setUserId(result.getParkUserId());
                vo.setParkId(SecurityUtils.getParkId());
                vo.setUserName(result.getUserName());
                vo.setPhone(result.getPhone());
                vo.setAddress(result.getAddress());
                return vo;
            }).collect(Collectors.toList());
            map.put("list", vos);
            map.put("total", vos.size());
            return AjaxResult.error("手机号已存在", map);
        } else {
            return AjaxResult.success("手机号码校验通过");
        }
    }

    @Override
    public Long addCarParkUserHandle(ParkCarAddRequest request, Long parkId) {
        if (null != request.getUserId()) {
            return request.getUserId();
        }
        if (StringUtils.isEmpty(request.getUserName())) {
            return null;
        }
        //添加或者绑定已有的baseUser
        BaseUser search = new BaseUser();
        search.setUserName(request.getUserName());
        search.setCellphone(request.getPhone());
        search.setAddress(request.getAddress());
        search.setRemark(request.getUserRemark());
        search.setTelephone(request.getTelephone());
        BaseUser baseUser = userAndBaseUserBizService.userAddOrGetBaseUser(search,"[移动端车辆管理新增车辆]");

        //创建新用户
        User user = new User();
        user.setBaseUserId(baseUser.getId());
        user.setParkId(parkId);
        user.setUserName(request.getUserName());
        user.setPhone(request.getPhone());
        user.setAddress(request.getAddress());
        userService.insertUser(user);
        return user.getId();
    }

    /**
     * 主要用于导入的车辆信息，姓名电话地址只在车辆表中有，需要在用户表中生成
     */
    @Override
    public ParkUserDTO parkUserHandle(ParkCar parkCar) {
        if (null == parkCar.getParkUserId() && (StringUtils.isNotEmpty(parkCar.getPhone()) && StringUtils.isNotEmpty(parkCar.getUserName()))) {
            BaseUser baseUser = new BaseUser();
            baseUser.setUserName(parkCar.getUserName());
            baseUser.setCellphone(parkCar.getPhone());
            baseUser.setAddress(parkCar.getAddress());
            int count = baseUserService.insertBaseUser(baseUser);
            if (0 < count) {
                User user = new User();
                user.setBaseUserId(baseUser.getId());
                user.setParkId(parkCar.getParkId());
                user.setUserName(parkCar.getUserName());
                user.setPhone(parkCar.getPhone());
                user.setAddress(parkCar.getAddress());
                userService.insertUser(user);
                //车辆更新--parkUserId赋值
                parkCar.setParkUserId(user.getId());
                parkCarService.updateParkCar(parkCar);
                ParkUserDTO parkUserDTO = new ParkUserDTO();
                parkUserDTO.setParkUserId(user.getId());
                parkUserDTO.setPhone(parkCar.getPhone());
                parkUserDTO.setUserName(parkCar.getUserName());
                parkUserDTO.setBaseUserId(baseUser.getId());
                parkUserDTO.setAddress(parkCar.getAddress());
                return parkUserDTO;
            } else {
                return null;
            }
        } else {
            ParkUserDTO parkUserDTO = new ParkUserDTO();
            parkUserDTO.setParkUserId(parkCar.getParkUserId());
            parkUserDTO.setPhone(parkCar.getPhone());
            parkUserDTO.setUserName(parkCar.getUserName());
            parkUserDTO.setAddress(parkCar.getAddress());
            return parkUserDTO;
        }
    }

    @Override
    public Long editCarParkUserHandle(ParkCarEditRequest request, Long parkId) {
        //车场管理编辑车辆目前不能编辑用户
        return request.getUserId();
    }

    /**
     * 保存车主信息
     * 1、如果userId不为空，
     * 2、如果userId为空，表示新增，先保存baseUser，再保存user
     */
    @Override
    public AjaxResult saveParkUser(ParkUserSaveRequest request) {
        Long userId = request.getUserId();
        if (null == userId) {
            BaseUser baseUser = new BaseUser();
            baseUser.setAddress(request.getAddress());
            baseUser.setTelephone(request.getTelephone());
            baseUser.setUserName(request.getUserName());
            baseUser.setRemark(request.getUserRemark());
            baseUser.setCellphone(request.getPhone());
            int count = baseUserService.insertBaseUser(baseUser);
            if (count > 0) {
                User user = new User();
                user.setBaseUserId(baseUser.getId());
                user.setParkId(SecurityUtils.getParkId());
                user.setUserName(request.getUserName());
                user.setPhone(request.getPhone());
                user.setAddress(request.getAddress());
                userService.insertUser(user);
                return AjaxResult.success("保存成功");
            } else {
                return AjaxResult.error("保存失败");
            }
        } else {
            User user = userService.selectUserById(userId);
            if (null != user) {
                Long baseUserId = user.getBaseUserId();
                if (null == baseUserId) {
                    return AjaxResult.error("保存失败。用户信息ID不存在");
                }
                BaseUser baseUser = baseUserService.selectBaseUserById(baseUserId);
                if (null == baseUser) {
                    return AjaxResult.error("保存失败。基本用户信息不存在");
                }
                baseUser.setAddress(request.getAddress());
                baseUser.setTelephone(request.getTelephone());
                baseUser.setUserName(request.getUserName());
                baseUser.setRemark(request.getUserRemark());
                baseUser.setCellphone(request.getPhone());
                int count = baseUserService.insertBaseUser(baseUser);
                if (count > 0) {
                    return AjaxResult.success("保存成功");
                } else {
                    return AjaxResult.error("保存失败");
                }
            } else {
                return AjaxResult.error("保存失败。用户信息不存在");
            }
        }
    }

    @Override
    public AjaxResult getWebParkUserList(ParkUserListRequest request) {
        ParkUserListSearch search = new ParkUserListSearch();
        search.setParkId(SecurityUtils.getParkId());
        search.setUserName(request.getUserName());
        search.setPhone(request.getPhone());
        search.setAddress(request.getAddress());
        search.setParam(request.getParam());
        List<ParkUserDTO> parkUserDTOList = userService.getParkUserList(search);
        List<Long> userIds = parkUserDTOList.stream().map(ParkUserDTO::getParkUserId).collect(Collectors.toList());

        List<ParkCar> parkCarList = parkCarService.selectParkCarListByUserIds(userIds);
        Map<Long, List<String>> userPlatesMap = new HashMap<>();
        parkCarList.forEach(item -> {
            List<String> plates = userPlatesMap.get(item.getParkUserId());
            if (CollUtil.isEmpty(plates)) {
                plates = new ArrayList<>();
            }
            plates.add(item.getBindPlates());
            userPlatesMap.put(item.getParkUserId(), plates);
        });

        List<ParkUserVo> vos = parkUserDTOList.stream().map(result -> {
            ParkUserVo vo = new ParkUserVo();
            vo.setUserId(result.getParkUserId());
            vo.setParkId(SecurityUtils.getParkId());
            vo.setUserName(result.getUserName());
            vo.setPhone(result.getPhone());
            vo.setAddress(result.getAddress());
            vo.setUserRemark(result.getUserRemark());
            vo.setTelephone(result.getTelephone());
            vo.setPlates(result.getPlates());
            if (CollUtil.isNotEmpty(userPlatesMap.get(result.getParkUserId()))) {
                vo.setPlates(StringUtils.join(userPlatesMap.get(result.getParkUserId()), ","));
            }
            return vo;
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(1);
        map.put("list", vos);
        map.put("total", vos.size());
        return AjaxResult.success(map);
    }

    @Override
    public Long addWebCarParkUserHandle(ParkCarAddRequest request, Long parkId) {
        if (null == request.getUserId()) {
            if (StringUtils.isNotEmpty(request.getPhone())) {
                List<User> userList = userService.selectUserByPhone(request.getParkId(), request.getPhone());
                if (!userList.isEmpty()) {
                    //手机号已经存在t_user，不新增
                    return userList.get(0).getId();
                }
            }
            //-------------------新增t_user流程开始--------------------
            Long baseUserId;
            //如果手机号不为空，查询是否存在baseUser
            if (StringUtils.isNotEmpty(request.getPhone())) {
                BaseUser baseUserSearch = new BaseUser();
                baseUserSearch.setCellphone(request.getPhone());
                List<BaseUser> baseUsers = baseUserService.selectBaseUserList(baseUserSearch);
                if (!baseUsers.isEmpty()) {
                    baseUserId = baseUsers.get(0).getId();
                } else {
                    //手机号不存在baseUser，新增baseUser
                    BaseUser baseUser = new BaseUser();
                    baseUser.setUserName(request.getUserName());
                    baseUser.setCellphone(request.getPhone());
                    baseUser.setAddress(request.getAddress());
                    baseUser.setRemark(request.getUserRemark());
                    baseUser.setTelephone(request.getTelephone());
                    baseUserService.insertBaseUser(baseUser);
                    baseUserId = baseUser.getId();
                }
            } else {
                //不存在手机号，直接新增baseUser
                BaseUser baseUser = new BaseUser();
                baseUser.setUserName(request.getUserName());
                baseUser.setCellphone(request.getPhone());
                baseUser.setAddress(request.getAddress());
                baseUser.setRemark(request.getUserRemark());
                baseUser.setTelephone(request.getTelephone());
                baseUserService.insertBaseUser(baseUser);
                baseUserId = baseUser.getId();
            }

            User user = new User();
            user.setBaseUserId(baseUserId);
            user.setParkId(parkId);
            user.setUserName(request.getUserName());
            user.setPhone(request.getPhone());
            user.setAddress(request.getAddress());
            user.setTelephone(request.getTelephone());
            user.setRemark(request.getUserRemark());
            userService.insertUser(user);
            //-------------------新增t_user流程结束--------------------

            return user.getId();

        } else {
            if (StringUtils.isNotEmpty(request.getIsUserUpdate()) && DictConstant.YES.equals(request.getIsUserUpdate())) {
                //更新用户：1、从request中取出parkUserId，查询user表，找出对应的user记录；user记录中找出baseUserId
                User user = userService.selectUserById(request.getUserId());
                user.setPhone(request.getPhone());
                user.setAddress(request.getAddress());
                user.setUserName(request.getUserName());
                user.setTelephone(request.getTelephone());
                user.setRemark(request.getUserRemark());
                userService.updateUser(user);

                Long baseUserId = user.getBaseUserId();
                if (null != baseUserId) {
                    BaseUser baseUser = new BaseUser();
                    baseUser.setId(baseUserId);
                    baseUser.setUserName(request.getUserName());
                    baseUser.setCellphone(request.getPhone());
                    baseUser.setAddress(request.getAddress());
                    baseUser.setRemark(request.getUserRemark());
                    baseUser.setTelephone(request.getTelephone());
                    baseUserService.updateBaseUser(baseUser);
                    return user.getId();
                } else {
                    return null;
                }

            } else {
                return request.getUserId();
            }
        }
    }

    @Override
    public Long editWebCarParkUserHandle(ParkCarEditRequest request, Long parkId) {
        if (null == request.getUserId()) {
            //新增用户
            BaseUser baseUser = new BaseUser();
            baseUser.setUserName(request.getUserName());
            baseUser.setCellphone(request.getPhone());
            baseUser.setAddress(request.getAddress());
            baseUser.setRemark(request.getUserRemark());
            baseUser.setTelephone(request.getTelephone());
            int count = baseUserService.insertBaseUser(baseUser);
            if (0 < count) {
                User user = new User();
                user.setBaseUserId(baseUser.getId());
                user.setParkId(parkId);
                user.setUserName(request.getUserName());
                user.setPhone(request.getPhone());
                user.setAddress(request.getAddress());
                user.setTelephone(request.getTelephone());
                user.setRemark(request.getUserRemark());
                userService.insertUser(user);
                return user.getId();
            } else {
                return null;
            }
        } else {
            if (StringUtils.isNotEmpty(request.getIsUserUpdate()) && DictConstant.YES.equals(request.getIsUserUpdate())) {
                // 更新用户：1、从request中取出parkUserId，查询user表，找出对应的user记录；user记录中找出baseUserId
                User user = userService.selectUserById(request.getUserId());
                user.setPhone(request.getPhone());
                user.setAddress(request.getAddress());
                user.setUserName(request.getUserName());
                user.setTelephone(request.getTelephone());
                user.setRemark(request.getUserRemark());
                userService.updateUser(user);

                Long baseUserId = user.getBaseUserId();
                if (null != baseUserId) {
                    BaseUser baseUser = new BaseUser();
                    baseUser.setId(baseUserId);
                    baseUser.setUserName(request.getUserName());
                    baseUser.setCellphone(request.getPhone());
                    baseUser.setAddress(request.getAddress());
                    baseUser.setRemark(request.getUserRemark());
                    baseUser.setTelephone(request.getTelephone());
                    baseUserService.updateBaseUser(baseUser);
                    return user.getId();
                } else {
                    return null;
                }

            } else {
                return request.getUserId();
            }
        }
    }

    /**
     * @param request
     * @author caogq
     * @description: 查询用户
     * @date: 2022/6/14 12:28
     * @Param [request]
     */
    @Override
    public AjaxResult conditionList(SelectParkUserRequest request) {
        Page<UserVo> page = new Page<>();
        page.setCurrent(request.getPageNum());
        page.setSize(request.getPageSize());

        IPage pageResult = userService.conditionList(request);

        List<User> userList = pageResult.getRecords();
        List<UserVo> userVos = new ArrayList<>();

        userList.stream().forEach(e -> {
            UserVo userVo = new UserVo();
            userVo.setId(e.getId());
            userVo.setUserName(e.getUserName());
            userVo.setGender(e.getGender());
            userVo.setPhone(e.getPhone());
            userVo.setAddress(e.getAddress());
            userVo.setRemark(e.getRemark());
            userVo.setStatus(e.getStatus());
            userVo.setVisitorCarType(e.getVisitorCarType());
            userVo.setBirthday(e.getBirthday());
            userVo.setCreateTime(e.getCreateTime());
            userVo.setUpdateTime(e.getUpdateTime());
            userVos.add(userVo);
        });

        Map<String, Object> map = new HashMap<>(3);
        map.put("list", userVos);
        map.put("total", pageResult.getTotal());
        map.put("totalSize", pageResult.getPages());
        return AjaxResult.success(map);
    }

    /**
     * @param ids
     * @author caogq
     * @description: 停车系统删除用户
     * @date: 2022/6/14 14:12
     * @Param [ids]
     */
    @Override
    @Transactional
    public AjaxResult delete(String ids) {

        List<String> userIds = Arrays.asList(ids.split(","));
//        if (userIds.size() == 1) {
//            Long userId = Long.valueOf(userIds.get(0));
//            ParkCar parkCar = new ParkCar();
//            parkCar.setParkUserId(userId);
//            List<ParkCar> parkCars = parkCarService.selectParkCarList(parkCar);
//            if (!parkCars.isEmpty()) {
//                return AjaxResult.error("用户已绑定车辆，无法删除！");
//            }
//            //baseUser约定暂时不删除
//            userService.deleteUserById(userId);
//            return AjaxResult.success();
//        }

        StringBuilder msg = new StringBuilder();
        for (String userId : userIds) {
            ParkCar parkCar = new ParkCar();
            parkCar.setParkUserId(Long.valueOf(userId));
            List<ParkCar> parkCars = parkCarService.selectParkCarList(parkCar);
            if (!parkCars.isEmpty()) {
                User user = userService.selectUserById(Long.valueOf(userId));
                msg.append("用户[" + user.getUserName() + "]已绑定车辆，无法删除！").append(Constants.BR);
                continue;
            }
            userService.deleteUserById(Long.valueOf(userId));
        }
        return AjaxResult.success(msg.toString());
    }

    /**
     * @param request
     * @author caogq
     * @description: 新增用户
     * @date: 2022/6/14 14:27
     * @Param [request]
     */
    @Override
    public AjaxResult add(AddUserRequest request) {
        User user = OrikaUtil.convert(request, User.class);
        AjaxResult result = userAndBaseUserBizService.addUser(user, "[PC车辆用户新增用户]");
        return result;
    }

    /**
     * @param request
     * @author caogq
     * @description: 修改用户
     * @date: 2022/6/14 14:27
     * @Param [request]
     */
    @Override
    @Transactional
    public AjaxResult update(UpdateUserRequest request) {
        User updateUser = OrikaUtil.convert(request, User.class);
        //处理用户数据
        AjaxResult result = userAndBaseUserBizService.updateUser(updateUser, "[PC车辆用户修改用户]");
        return result;
    }


}
